package com.thingple.usb.session;

import android.hardware.usb.UsbAccessory;
import android.hardware.usb.UsbManager;
import android.util.Log;

import com.thingple.usb.stream.InputOutputProcessor;
import com.thingple.util.Strings;

public class UsbSessionImpl extends SerialSession implements UsbSession {

    private static final String TAG = UsbSessionImpl.class.getName();

    private InputOutputProcessor ioProcessor;

    public UsbSessionImpl(UsbManager usbManager, UsbAccessory device, int baudRate) {
        super(usbManager, device, baudRate);
        init();
    }

    @Override
    protected void init() {
        super.init();
    }

    protected boolean exec() {
        try{
            ioProcessor = initStreamProcessor();
            boolean ioEnabled = ioProcessor.initIO(usbManager, device, new InputOutputProcessor.ProcessFunc() {
                @Override
                public void handle(InputOutputProcessor processor) {
                    execIoProcess();
                }
            });
            if (!ioEnabled) {
                return false;
            }
        } finally {
            if (ioProcessor != null) {
                ioProcessor.onDestroy();
                ioProcessor = null;
            }
        }
        return false;
    }
    private InputOutputProcessor initStreamProcessor() {
        InputOutputProcessor sp = new InputOutputProcessor();
        sp.setStreamUpListener(this::onRx);
        sp.setStreamDownListener(this::onTx);
        sp.setErrorListener(this::onErr);
        sp.setTraceListener(this::onTrace);
        return sp;
    }
    private void execIoProcess() {
        byte[] configCmd = SetConfig(baudRate, SerialPortConfig.DataBits8, (byte)0x01, (byte)0x00, (byte)0x00);
        ioProcessor.write(configCmd);
        Log.d(TAG, "开始io_processor循环");
        ioProcessor.loop();
    }

    @Override
    public void write(byte[] payload) {
        Log.d(TAG, "tx:" + Strings.hex(payload));
        if (ioProcessor != null) {
            ioProcessor.write(payload);
        }
    }
    @Override
    public void writeAsync(byte[] payload) {
        Log.d(TAG, "tx:" + Strings.hex(payload));
        if (ioProcessor != null) {
            ioProcessor.writeAsync(payload);
        }
    }
    @Override
    public void destroy() {
        Log.d(TAG, "清理usb_session");
        if (ioProcessor != null) { // 一定要通知关闭(里面有一个循环)
            ioProcessor.stop();
        }
        stop(); // 关闭线程
        super.destroy();
    }
}
